<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="产品类型" prop="type">
        <treeselect v-model="queryParams.type" :options="productTypeOptions" :normalizer="normalizer" placeholder="选择产品类型" style="width: 180px"/>
      </el-form-item>
      <el-form-item label="行业" prop="industry">
        <treeselect v-model="queryParams.industry" :options="solutionOptions" :normalizer="normalizer" placeholder="选择产品类型" style="width: 180px"/>
      </el-form-item>
      <el-form-item label="产品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入产品名称" :maxlength="30" show-word-limit clearable style="width: 220px" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择" style="width: 100px" clearable>
          <el-option
            v-for="dict in dict.type.business_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-upload2" size="mini" @click="handleOnline">上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="handleOffline">下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="productList" row-key="id"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="产品名称" prop="name" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="产品类型" prop="typeName" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="行业解决方案" prop="industryName" width="120" :show-overflow-tooltip="true"/>
      <el-table-column label="首页是否显示" align="center" prop="ifIndex" width="100">
        <template slot-scope="scope">
          <el-switch 
            v-model="scope.row.ifIndex"
            active-value="1"
            inactive-value="0"
            @change="handleUpdateIfIndex(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="70">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.business_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" width="60" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-upload" @click="handleUpdateImg(scope.row)">设置文描</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdateSpec(scope.row)">设置参数</el-button>
          <el-button v-if="scope.row.status !== '1'" size="mini" type="text" icon="el-icon-upload2" @click="handleOnline(scope.row)">上架</el-button>
          <el-button v-if="scope.row.status === '1'" size="mini" type="text" icon="el-icon-download" @click="handleOffline(scope.row)">下架</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditSeo(scope.row)">SEO设置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <seoDetail ref="seo" />

    <!-- 添加或修改产品对话框 -->
    <el-dialog :visible.sync="open" :title="title" width="90%" :close-on-click-modal="false" append-to-body>
      <div class="product_info">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item title="产品基础信息" name="1">
            <el-row :gutter="10" class="mb8">
              <el-col :span="11">
                <el-form-item label="产品类型" prop="type">
                  <treeselect v-model="form.type" :options="productTypeOptions" :normalizer="normalizer" placeholder="选择产品类型" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行业解决方案" prop="industry">
                  <treeselect v-model="form.industry" :options="solutionOptions" :normalizer="normalizer" placeholder="选择行业解决方案" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="23">
                <el-form-item label="产品名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入产品名称" :maxlength="30" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="23">
                <el-form-item label="产品简介" prop="remark">
                  <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 9999}" v-model="form.remark" placeholder="请输入产品简介" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="23">
                <el-form-item label="产品详情" prop="content">
                  <myeditor v-model="form.content" v-if="open" />
                  <!-- <editor v-model="form.content" /> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="显示排序" prop="sort">
                  <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="产品文描" name="2">
            <el-row>
              <el-col :span="24">
                <el-form-item label="主图" prop="mainImg" style="height:120px;">
                  <mainImg :product="form" @saveFile="setMainImg" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="轮播图" prop="listImg" style="height:120px;">
                  <listImg :product="form" @saveFile="setListImg" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin-top: 20px;">
              <el-col :span="16">
                <el-form-item label="视频" prop="video">
                  <video ref="videoRef" 
                    :src="basePath + form.video" 
                    width="300" 
                    height="250"
                    controls>
                    </video>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-button class="video-upload"
                    type="info"
                    plain
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                  >上传</el-button>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item title="产品参数" name="3" v-if="form.id === undefined || dictType !== undefined">
            <div class="el-table el-table--enable-row-hover el-table--medium">
            <table cellspacing="0" class="spec_table">
              <tbody>
                <template v-if="dictType !== undefined">
                  <tr v-for="(obj,index) in dict.type[dictType]">                  
                    <td class="el-table__cell is-leaf">{{ obj.label }}</td>
                    <td class="el-table__cell is-leaf">
                      <template v-if="form.specData !== undefined">
                        <el-form-item :prop="`specData.${obj.value}`">
                        <el-input v-model="form.specData[obj.value]" @input="changeMessage()" />
                        </el-form-item>
                      </template>
                    </td>
                  </tr>
                </template>
              </tbody>
            </table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".mp4, .avi, .rmvb"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-error="handleUploadError"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <p>仅允许导入mp4、avi、rmvb格式的视频文件</p>
          <p>大小不超过 <b style="color: #f56c6c">100MB</b></p>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, addProduct, updateProduct, deleteProduct, batchUpdateProductStatus, changeProductIfIndex, updateProductStatus } from "@/api/product/list";
import { listProductType, getDictType} from "@/api/product/type";
import { listSolution } from "@/api/product/solution";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Product",
  dicts: [
    'business_status',
    'product_type_1',
    'product_type_5',
    'product_type_9',
    'product_type_18',
    'product_type_17',
  ],
  components: {
    Treeselect,
    mainImg: () => import('./mainImg'),
    listImg: () => import('./listImg'),
    seoDetail: () => import('@/views/content/seo/detail'),
},
  data() {
    return {
      basePath: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openImg: false,
      openSpec: false,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品类型表格数据
      productList: [],
      // 产品类型树
      productTypeOptions:[],
      // 行业解决方案树
      solutionOptions:[],
      // 默认展开基础信息
      activeName: '1',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: undefined,
        industry: undefined,
        name: undefined,
        status: undefined,
      },
      dictType: undefined,
      // 表单参数
      form: {
        specData:{},
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        type: [
           { required: true, message: "产品类型不能为空", trigger: "blur" }
        ],
        industry: [
           { required: true, message: "产品行业不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序值不能为空", trigger: "blur" }
        ],
        remark: [
           { required: true, message: "产品概述不能为空", trigger: "blur" }
        ],
        content: [
           { required: true, message: "产品详情不能为空", trigger: "blur" }
        ],
        mainImg: [
           { required: true, message: "产品主图不能为空", trigger: "blur" }
        ],
        listImg: [
           { required: true, message: "产品轮播图不能为空", trigger: "blur" }
        ],
        video: [
           { required: true, message: "产品视频不能为空", trigger: "blur" }
        ],
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/product/uploadVideo"
      },
      seoData: {},
      diaShow: false,
    };
  },
  watch: {
    'form.type': 'handleTypeChange',
  },
  computed: {
    /*videoUrl() { 
      return `${process.env.VUE_APP_BASE_API}${this.form.video}`;
    }*/
    /*dictData: function(){
      if(this.dictType === undefined) {
        return undefined;
      }
      const dicts = this.$store.getters.dict;
      for(let i=0; i<dicts.length; i++) {
        if(dicts[i].key === this.dictType) {
          return dicts[i].value;
        }
      }
      return undefined;
    }*/
  },
  created() {
    this.getProductTypeList();
    this.getSoluctionList();
    this.getList();
  },
  methods: {
    getProductTypeList() {
      listProductType().then(response => {
        this.productTypeOptions = this.handleTree(response.data, "id");
      });
    },
    getSoluctionList() {
      listSolution().then(response => {
        this.solutionOptions = this.handleTree(response.data, "id");
      });
    },
    /** 转换数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
          this.productList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.multiple = !selection.length;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    }, 
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.open = true;
      this.title = "添加产品";
      this.activeName = '1';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getProduct(id).then(response => {
        this.form = response.data;
        let specStr = this.form.spec;
        if (specStr !== undefined && specStr !== '') {
          this.form.specData = JSON.parse(specStr);
        }
        this.dictType = this.form.typeDictType;
        this.open = true;
        this.title = "修改产品";
        this.activeName = '1';
      });
    },
    handleOnline(row) {
      // 上架
      if (row.id !== undefined) {
        // 单个
        updateProductStatus({'id':row.id, 'status':'1'}).then(() => {
          this.$modal.msgSuccess('上架成功');
          this.getList();
        }).catch(() => {});
      } else if (this.ids !== undefined && this.ids.length > 0) {
        batchUpdateProductStatus({'ids':this.ids, 'status':'1'}).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      } else {
        this.$modal.msgError("请选中要上架的商品");
      }
    },
    handleOffline(row) {
      // 下架
      if (row.id !== undefined) {
        // 单个
        updateProductStatus({'id':row.id, 'status':'2'}).then(() => {
          this.$modal.msgSuccess('下架成功');
          this.getList();
        }).catch(() => {});
      } else if (this.ids !== undefined && this.ids.length > 0) {
        batchUpdateProductStatus({'ids':this.ids, 'status':'2'}).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      } else {
        this.$modal.msgError("请选中要下架的商品");
      }
    },
    handleUpdateImg(row) {
      this.reset();
      const id = row.id;
      getProduct(id).then(response => {
        this.form = response.data;
        let specStr = this.form.spec;
        if (specStr !== undefined && specStr !== '') {
          this.form.specData = JSON.parse(specStr);
        }
        this.dictType = this.form.typeDictType;
        this.open = true;
        this.title = "修改产品";
        this.activeName = '2';
      });
    },
    handleUpdateSpec(row) {
      this.reset();
      const id = row.id;
      getProduct(id).then(response => {
        this.form = response.data;
        let specStr = this.form.spec;
        if (specStr !== undefined && specStr !== '') {
          this.form.specData = JSON.parse(specStr);
        }
        this.dictType = this.form.typeDictType;
        this.open = true;
        this.title = "修改产品";
        this.activeName = '3';
      });
    },
    handleUpdateIfIndex(row) {
      // 修改产品是否在首页展示
      let text = row.ifIndex === "0" ? "不展示" : "展示";
      this.$modal.confirm('确认要在首页"' + text + '"产品 "' + row.name + '"吗？').then(function() {
        if (row.ifIndex === '1' && row.status !== '1') {
          this.$modal.msgError("设置首页展示必须是上架状态");
          return;
        }
        return changeProductIfIndex(row.id, row.ifIndex);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.ifIndex === "0" ? "1" : "0";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('是否确认删除参数编号为"' + id + '"的数据项？').then(() => {
          deleteProduct(id).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {})
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.spec = JSON.stringify(this.form.specData);
          if (this.form.id != undefined) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(() => {});
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(() => {});
          }
        }
      });
    },
    /**设置主图 */
    setMainImg(file) {
      this.form.mainImg = file;
    },
    setListImg(file) {
      this.form.listImg = file;
    },
    /**上传视频 */
    handleImport() {
      this.upload.title = "视频上传";
      this.upload.open = true;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.form.video = response.videoUrl;
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "修改结果", { dangerouslyUseHTMLString: true });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    changeMessage() {
      this.$forceUpdate();
    },
    handleTypeChange(productType) {
      if(productType === undefined) {
        this.dictType = undefined;
        //this.form.typeDictType = undefined;
        return;
      }
      getDictType(productType).then(response => {
        //this.form.typeDictType = response.data;
        this.dictType = response.data;
        this.form.specData = {};
      });
    },
    handleEditSeo(row) {
      this.seoData.pageType = 'product',
      this.seoData.pageId = row.id;
      this.$refs.seo.open(this.seoData);
    },
  }
}
</script>
<style scoped lang="scss">
.video-upload {
  position:absolute;
  top:50%;
  transform: translateY(-50%);
}

.spec_table {
  width: 90%;
}

/**
  * 用不着了
  */
.spec_table .el-form-item {
  margin-bottom: 0;
}

/**
  *  这个样式没有生效 只能说我尽力了 用不着了
  */
.el-table__cell > .el-form-item > .el-form-item__content {
  margin-left: 0px !important;
}

.product_info {
  height: 500px;
  overflow-y: auto;
}
</style>